<template>
  <div class="app-container">
    <!-- 顶部时间筛选 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <!-- 移除时间筛选控件，只保留搜索按钮 -->
      <el-form-item class="search">
        <el-button type="primary" @click="handleQuery">搜索</el-button>
      </el-form-item>
    </el-form>
    <div class="dashboard-container">
      <!-- 左侧主要内容区域 -->
      <div class="main-content">
         <!-- 统计数据卡片 -->
        <div class="stats-cards">
          <div class="stat-item">
            <div class="stat-icon orders-icon">
              <i class="el-icon-document"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">今日订单总数</div>
              <div class="stat-value">{{ dashboardData.todayOrderCount || 0 }}</div>
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-icon sales-icon">
              <i class="el-icon-coin"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">今日销售总额</div>
              <div class="stat-value">¥ {{ dashboardData.todayOrderTotalPrice || '0' }}</div>
            </div>
          </div>

          <div class="stat-item">
            <div class="stat-icon yesterday-icon">
              <i class="el-icon-data-line"></i>
            </div>
            <div class="stat-content">
              <div class="stat-label">昨日销售总额</div>
              <div class="stat-value">¥ {{ dashboardData.yesterdayOrderTotalPrice || '0' }}</div>
            </div>
          </div>
        </div>
        <!-- 顶部三个功能卡片 -->
        <div class="top-cards">
          <el-card class="feature-card">
            <div class="card-header">
              <span class="card-title">会员总数</span>
            </div>
            <div class="card-content">
              <div class="feature-link">{{ dashboardData.userCount || '0' }}</div>
            </div>
          </el-card>

          <el-card class="feature-card">
            <div class="card-header">
              <span class="card-title">今日新增会员</span>
            </div>
            <div class="card-content">
              <div class="feature-link">{{ dashboardData.todayUserCount || '0'  }}</div>
            </div>
          </el-card>

          <el-card class="feature-card">
            <div class="card-header">
              <span class="card-title">本月新增会员</span>
            </div>
            <div class="card-content">
              <div class="feature-link">{{ dashboardData.monthUserCount || '0'  }}</div>
            </div>
          </el-card>
        </div>

        <!-- 待处理事务 -->
        <el-card class="pending-tasks">
          <div slot="header" class="clearfix">
            <span>订单</span>
          </div>
          <div class="task-grid">
            <div class="task-column">
              <div class="task-item">
                <span>待付款订单</span>
                <span class="task-count">{{ dashboardData.waitPayOrderCount || '0'  }}</span>
              </div>
              <div class="task-item">
                <span>待发货订单</span>
                <span class="task-count">{{ dashboardData.waitSendOrderCount || '0'  }}</span>
              </div>
              <div class="task-item">
                <span>待确认收货订单</span>
                <span class="task-count">{{ dashboardData.waitConfirmOrderCount || '0'  }}</span>
              </div>
            </div>
            <div class="task-column">
              <div class="task-item">
                <span>已完成订单</span>
                <span class="task-count">{{ dashboardData.waitReceiveOrderCount || '0'  }}</span>
              </div>
              <div class="task-item">
                <span>已退款订单</span>
                <span class="task-count">{{ dashboardData.refundedOrderCount || '0'  }}</span>
              </div>
              <div class="task-item">
                <span>待退货订单</span>
                <span class="task-count">{{ dashboardData.waitRefundOrderCount || '0'  }}</span>
              </div>
            </div>
          </div>
        </el-card>

        <!-- 商品和用户统计 -->
        <div class="bottom-stats">
          <el-card class="stats-card">
            <div slot="header" class="clearfix">
              <!-- <span>商品总数</span> -->
            </div>
            <div class="stats-grid">
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.monthOrderCount || '0'  }}</div>
                <div class="stats-label">本月订单总数</div>
              </div>
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.monthOrderTotalPrice || '0'  }}</div>
                <div class="stats-label">本月销售总额</div>
              </div>
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.lastMonthOrderCount || '0'  }}</div>
                <div class="stats-label">上月订单总数</div>
              </div>
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.lastMonthOrderTotalPrice || '0'  }}</div>
                <div class="stats-label">上月销售总额</div>
              </div>
            </div>
          </el-card>

          <el-card class="stats-card">
            <div slot="header" class="clearfix">
              <!-- <span>用户总数</span> -->
            </div>
            <div class="stats-grid">
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.weekOrderCount || '0'  }}</div>
                <div class="stats-label">本周订单总数</div>
              </div>
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.weekOrderTotalPrice || '0'  }}</div>
                <div class="stats-label">本周销售总额</div>
              </div>
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.lastWeekOrderCount || '0'  }}</div>
                <div class="stats-label">上周订单总数</div>
              </div>
              <div class="stats-item">
                <div class="stats-number">{{ dashboardData.lastWeekOrderTotalPrice || '0'  }}</div>
                <div class="stats-label">上周销售总额</div>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 订单统计折线图 -->
        <el-card class="chart-card">
          <div style="position: relative; min-height: 40px;">
            <!-- 时间查询条件放到右上角 -->
            <div class="chart-date-range">
              <el-date-picker
                v-model="queryParams.dateRange"
                style="width: 240px"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                size="small"
                @change="handleQuery"
              ></el-date-picker>
            </div>
            <div class="chart-container">
              <div ref="orderChart" style="width: 100%; height: 400px;"></div>
            </div>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { homeInfo } from "@/api/home";
import * as echarts from 'echarts';

// 日期格式化函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

export default {
  name: "Index",
  data() {
    const today = new Date();
    const todayStr = formatDate(today);
     // 计算一个月前的日期
    const oneMonthAgo = new Date();
    oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
    const oneMonthAgoStr = formatDate(oneMonthAgo);

    return {
      // 显示搜索条件
      showSearch: false,
      queryParams: {
         dateRange: [oneMonthAgoStr, todayStr],
      },
      dashboardData: {
        todayOrders: 200,
        todaySales: '5000.00',
        yesterdaySales: '5000.00'
      },
      chartDateRange: ['2018-11-01', '2018-11-06'],
      orderChart: null,
      // 添加图表数据
      chartData: null
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  created() {
    this.getList();
  },
  beforeDestroy() {
    if (this.orderChart) {
      this.orderChart.dispose();
    }
  },
  methods: {
    /** 获取系统设置数据 */
    async getList() {
      try {
        const response = await homeInfo({
          startTime: this.queryParams.dateRange[0],
          endTime: this.queryParams.dateRange[1]
        });
        console.log("response --- ", response);
        // 这里可以根据接口返回的数据更新dashboardData
        if (response && response.data) {
          this.dashboardData =  response.data ;
        }
      } catch (error) {
        console.error('获取首页数据失败:', error);
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 初始化图表 */
    initChart() {
      if (!this.$refs.orderChart) return;

      this.orderChart = echarts.init(this.$refs.orderChart);

      // 使用真实数据或默认数据
      const chartData = this.chartData || [];

      // 提取日期、订单数量和价格数据
      const dates = chartData.map(item => {
        const date = new Date(item.day);
        return `${date.getMonth() + 1}-${date.getDate()}`; // 格式化为 MM-DD
      });
      const orderCounts = chartData.map(item => item.orderCount);
      const orderPrices = chartData.map(item => parseFloat(item.orderPrice));

      const option = {
        title: {
          text: `总订单: ${orderCounts.reduce((sum, count) => sum + count, 0)}`,
          left: 'left',
          textStyle: {
            fontSize: 18,
            fontWeight: 'bold',
            color: '#333'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          },
          formatter: function(params) {
            let result = `${params[0].axisValue}<br/>`;
            params.forEach(param => {
              result += `${param.seriesName}: ${param.value}<br/>`;
            });
            return result;
          }
        },
        legend: {
          data: ['订单数量', '订单价格'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: 100,
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLine: {
            lineStyle: {
              color: '#e6e6e6'
            }
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: '#999',
            interval: Math.floor(dates.length / 10) // 控制显示的标签数量
          }
        },
        yAxis: [
          {
            type: 'value',
            name: '订单数量',
            position: 'left',
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#999'
            },
            splitLine: {
              lineStyle: {
                color: '#f0f0f0'
              }
            }
          },
          {
            type: 'value',
            name: '订单价格',
            position: 'right',
            axisLine: {
              show: false
            },
            axisTick: {
              show: false
            },
            axisLabel: {
              color: '#999',
              formatter: '¥{value}'
            },
            splitLine: {
              show: false
            }
          }
        ],
        series: [
          {
            name: '订单数量',
            type: 'line',
            yAxisIndex: 0,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#00D4AA',
              width: 3
            },
            itemStyle: {
              color: '#00D4AA'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(0, 212, 170, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(0, 212, 170, 0.1)'
                  }
                ]
              }
            },
            data: orderCounts
          },
          {
            name: '订单价格',
            type: 'line',
            yAxisIndex: 1,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            lineStyle: {
              color: '#409EFF',
              width: 3
            },
            itemStyle: {
              color: '#409EFF'
            },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0,
                y: 0,
                x2: 0,
                y2: 1,
                colorStops: [
                  {
                    offset: 0,
                    color: 'rgba(64, 158, 255, 0.3)'
                  },
                  {
                    offset: 1,
                    color: 'rgba(64, 158, 255, 0.1)'
                  }
                ]
              }
            },
            data: orderPrices
          }
        ]
      };

      this.orderChart.setOption(option);

      // 监听窗口大小变化
      window.addEventListener('resize', () => {
        if (this.orderChart) {
          this.orderChart.resize();
        }
      });
    },

    /** 获取系统设置数据 */
    async getList() {
      console.log("--------------------", this.queryParams);
      try {
        const response = await homeInfo({
          startTime: this.queryParams.dateRange[0],
          endTime: this.queryParams.dateRange[1]
        });
        console.log("response --- ", response);
        // 更新图表数据
        if (response && response.data && response.data.dayList) {
          this.chartData = response.data.dayList;
          // 重新初始化图表
          if (this.orderChart) {
            this.orderChart.dispose();
          }
          this.$nextTick(() => {
            this.initChart();
          });
        }
        // 更新其他数据
        if (response && response.data) {
          this.dashboardData = { ...this.dashboardData, ...response.data };
        }
      } catch (error) {
        console.error('获取首页数据失败:', error);
      }
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.dashboard-container {
  display: flex;
  gap: 20px;
}

.main-content {
  flex: 1;
}

.sidebar {
  width: 300px;
}

/* 顶部功能卡片 */
.top-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.feature-card {
  min-height: 120px;
}

.card-header {
  margin-bottom: 15px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.feature-link {
  color: #409EFF;
  cursor: pointer;
  font-size: 14px;
}

.feature-link:hover {
  text-decoration: underline;
}

/* 统计数据卡片 */
.stats-cards {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 15px;
  font-size: 24px;
  color: #fff;
}

.orders-icon {
  background: #409EFF;
}

.sales-icon {
  background: #67C23A;
}

.yesterday-icon {
  background: #E6A23C;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

/* 待处理事务 */
.pending-tasks {
  margin-bottom: 20px;
}

.task-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

.task-column {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #f0f0f0;
}

.task-item:last-child {
  border-bottom: none;
}

.task-count {
  color: #F56C6C;
  font-weight: bold;
}

/* 底部统计 */
.bottom-stats {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stats-card {
  min-height: 200px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20px;
}

.stats-item {
  text-align: center;
  padding: 20px;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #333;
  margin-bottom: 10px;
}

.stats-label {
  font-size: 14px;
  color: #666;
}

/* 图表卡片 */
.chart-card {
  margin-bottom: 20px;
}

.chart-date-range {
  display: flex;
  align-items: center;
  gap: 10px;
  position: absolute;
  top: 10px;
  right: 20px;
  z-index: 2;
  background: #fff;
  padding-left: 8px;
  font-size: 14px;
}

.chart-container {
  margin-top: 0;
}

/* 二维码卡片 */
.qr-card {
  height: fit-content;
}

.qr-content {
  text-align: center;
  padding: 20px;
}

.qr-code {
  margin-bottom: 15px;
}

.qr-placeholder {
  width: 150px;
  height: 150px;
  border: 2px dashed #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  font-size: 48px;
  color: #ccc;
}

.qr-text {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.qr-text p {
  margin: 5px 0;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .dashboard-container {
    flex-direction: column;
  }

  .sidebar {
    width: 100%;
  }

  .top-cards,
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
  }
}

@media (max-width: 768px) {
  .top-cards,
  .stats-cards,
  .bottom-stats {
    grid-template-columns: 1fr;
  }

  .task-grid {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.el-divider {
  margin: 30px 0 20px 0;
}

.el-divider:first-of-type {
  margin-top: 0;
}

.box-card {
  margin: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both;
}
</style>
